﻿using Prism.Commands;
using Prism.Events;
using Prism.Regions;
using System;
using System.Threading.Tasks;
using System.Timers;
using PrismPractice.Const;
using PrismPractice.Core.Mvvm;
using WPFTemplateLib.Controls.WpfToast;

namespace PrismPractice.ViewModels
{
	public class MainWindowViewModel : ViewModelBase
	{
		#region 成员

		/// <summary>
		/// 区域管理器
		/// </summary>
		private readonly IRegionManager _regionManager;

		/// <summary>
		/// 事件聚合器
		/// </summary>
		private readonly IEventAggregator _eventAggregator;

		/// <summary>
		/// 刷新时间的定时器
		/// </summary>
		private readonly Timer _timerRefreshTime = new Timer() { Interval = 1000, AutoReset = true, Enabled = true };

		public MainWindowViewModel(IRegionManager regionManager, IEventAggregator eventAggregator) : base(nameof(MainWindowViewModel))
		{
			_regionManager = regionManager;

			_eventAggregator = eventAggregator;
			_eventAggregator.GetEvent<EnterSecondaryInterfaceEvent>().Subscribe(EnterSecondaryInterface);
			_eventAggregator.GetEvent<ReturnToFirstInterfaceEvent>().Subscribe(ReturnToFirstInterface);

			_timerRefreshTime.Elapsed += TimerRefreshTime_Elapsed;

			_ = InitAsync();
		}

		/// <summary>
		/// 异步初始化方法
		/// </summary>
		private async Task InitAsync()
		{
			await Task.Yield();

			ExecuteSwitchPageCmd(ViewNames.MAIN_VIEW);
		}

		~MainWindowViewModel()
		{
			_timerRefreshTime.Stop();
			_timerRefreshTime.Dispose();
		}

		#endregion

		#region 绑定

		public string Title { get; set; } = "Prism Application";

		/// <summary>
		/// 是否是二级界面
		/// </summary>
		public bool IsSecondaryInterface { get; set; }

		/// <summary>
		/// 页面切换时顶部显示的文字
		/// </summary>
		public string CurrentPageName { get; set; }

		/// <summary>
		/// 当前时间
		/// </summary>
		public DateTime CurrentTime { get; set; }

		#endregion

		#region 命令

		#region [命令] 载入事件
		private DelegateCommand _LoadedCmd;
		public DelegateCommand LoadedCmd => _LoadedCmd ??= new DelegateCommand(ExecuteLoadedCmd);
		#endregion

		#region [命令] 切换页面命令
		private DelegateCommand<string> _SwitchPageCmd;
		public DelegateCommand<string> SwitchPageCmd => _SwitchPageCmd ??= new DelegateCommand<string>(ExecuteSwitchPageCmd);
		#endregion

		#region [命令] 退出
		private DelegateCommand _ExitCmd;
		public DelegateCommand ExitCmd => _ExitCmd ??= new DelegateCommand(ExecuteExitCmd);
		private void ExecuteExitCmd()
		{
			Environment.Exit(0);
		}
		#endregion

		#endregion

		#region 方法

		/// <summary>
		/// 刷新时间
		/// </summary>
		private void TimerRefreshTime_Elapsed(object sender, ElapsedEventArgs e)
		{
			Dispatcher?.Invoke(() =>
			{
				CurrentTime = DateTime.Now;
			});
		}

		private void ExecuteLoadedCmd()
		{
			Title = "Prism Example Application"; //测试绑定和命令是否正常；
		}

		/// <summary>
		/// 命令执行方法：切换页面命令
		/// </summary>
		/// <param name="pageName">页面名称</param>
		private void ExecuteSwitchPageCmd(string pageName)
		{
			_regionManager.RequestNavigate(RegionNames.ContentRegion, pageName, navigationResult =>
			{
				if (navigationResult.Result == null || navigationResult.Result == false)
				{
					ToastToScreen($"Switch page error：{navigationResult.Error.Message}", ToastIcons.Error);
				}
				else
				{
					switch (pageName)
					{
						case ViewNames.LOGIN_VIEW:
							CurrentPageName = "LOG IN";
							break;
						case ViewNames.DATA_LOG_VIEW:
							CurrentPageName = "DATA LOG";
							break;
						default:
							CurrentPageName = pageName;
							break;
					}
				}
			});
		}

		/// <summary>
		/// 进入二级界面
		/// </summary>
		/// <param name="viewName">页面名称</param>
		private void EnterSecondaryInterface(string viewName)
		{
			_regionManager.RequestNavigate(RegionNames.SecondaryContentRegion, viewName, navigationResult =>
			{
				if (navigationResult.Result == null || navigationResult.Result == false)
				{
					ToastToScreen($"Switch page error：{navigationResult.Error.Message}", ToastIcons.Error);
				}
				else
				{
					IsSecondaryInterface = true;
				}
			});
		}

		/// <summary>
		/// 返回一级界面
		/// </summary>
		private void ReturnToFirstInterface()
		{
			IsSecondaryInterface = false;
		}

		#endregion
	}
}
